package net.dopan.pigframe.demo.service.ribbon;

import net.dopan.pigframe.config.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Service
public class OssServerRibbon {
    @Autowired
    private RestTemplate restTemplate;

    public String getConfig() {
        return restTemplate.getForObject("http://OSSSERVER/api/config", String.class);

    }

    public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
        String filePath = FileUtils.uploadImage(request, file);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);
        File newFile = new File(filePath);
        FileSystemResource resource = new FileSystemResource(newFile);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("file", resource);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange("http://OSSSERVER/api/upload", HttpMethod.POST, httpEntity, String.class);
        System.out.println(responseEntity.getBody());
        /** 删除本地图片 */
        newFile.delete();
        return responseEntity.getBody();
    }
}
